﻿using SuperX.Common;
using SuperX.Common.APIManager;
using SuperX.Common.Log;
using SuperX.Common.Respository;
using System;

namespace SuperX.WebAppService
{
    public class WebAppServer : HostService
    {
        public override string ServiceType { get; set; }
        private WebAppHost WebAppHost { get; set; }
        public WebAppConfig Config { get; set; }

        private DynamicApiController Controller;

        public override bool Exit()
        {
            return true;
        }

        public override bool Init()
        {
            WebAppHost = new WebAppHost(Config);
            Controller = new WebAppServiceController(this);
            return true;
        }

        public override bool Load(string fileName)
        {
            FileName = fileName;
            Repository = new JsonRepository(FileName);
            Repository.Load(typeof(WebAppConfig));
            Config = Repository.Model as WebAppConfig;
            if (Config == null)
            {
                CreateCfgFile();
            }
            return true;
        }

        private void CreateCfgFile()
        {
            WebAppConfig webAppConfig = new WebAppConfig();
            webAppConfig.ListeningAddress.IP = "127.0.0.1";
            webAppConfig.ListeningAddress.Port = 9000;
            Config = webAppConfig;
            SaveAs(FullFileName);
        }

        public override bool SaveAs(string fileName)
        {
            Repository = new JsonRepository(fileName) { Model = Config };
            Repository.Save();
            return true;
        }

        public override bool Start()
        {
            Logger.Info($"{this.GetType().Name}启动");
            WebAppHost.Start();
            return true;
        }

        public override bool Stop()
        {
            Logger.Info($"{GetType().Name}停止...");
            try
            {
                WebAppHost?.Stop();
                Controller = null;
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
            }
            return true;
        }
    }
}